<template>
  <div class="createPost-container">
    <el-form v-if="mystep==='create'" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="200px" inline="true">
      <div />
      <el-form-item label="督办单位" prop="roomNo">
        <el-input v-model.trim="postForm.roomNo" style="width:610px" />
      </el-form-item>
      <div />
      <el-form-item label="被督办单位" prop="roomNo">
        <el-input v-model.trim="postForm.roomNo" style="width:610px" />
      </el-form-item>
      <div />
      <el-form-item label="督办时间" prop="money">
        <el-date-picker v-model.trim="postForm.money" style="width:200px" />
      </el-form-item>
      <el-form-item label="督办期限" prop="roomNo">
        <el-input v-model.trim="postForm.roomNo" style="width:200px" />
      </el-form-item>
      <div />
      <el-form-item label="督办事项" prop="money">
        <el-input v-model.trim="postForm.roomNo" style="width:610px" />
      </el-form-item>
      <div />
      <el-form-item style="margin-left: 200px;">
        <el-button type="primary" :loading="loading" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>

const defaultForm = {
  faultClassCode: '',
  description: '',
  submitDeptId: '',
  submitUserId: '',
  roomNo: '',
  telephone: '',
  priority: '',
  flowType: '',
  id: null
}
const defaultForm1 = {
  approveContent: '',
  approveResult: ''
}
const defaultForm2 = {
  processUserId: ''
}
const defaultForm3 = {
  analysis: '',
  solving: '',
  completed: ''
}
const defaultForm4 = {
  passed: '',
  closeReason: ''
}
const defaultForm5 = {
  evaluateResult: ''
}

export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      myid: 0,
      roleName: '',
      deptName: '',
      realName: '',
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      postForm1: Object.assign({}, defaultForm1),
      postForm2: Object.assign({}, defaultForm2),
      postForm3: Object.assign({}, defaultForm3),
      postForm4: Object.assign({}, defaultForm4),
      postForm5: Object.assign({}, defaultForm5),
      loading: false,
      deptOption: [],
      userOption: [],
      processUserOption: [],
      priorityOption: [],
      classCodeOption: [],
      flowTypeOption: [],
      rules: {
        faultClassCode: [{ validator: validateRequire }],
        description: [{ validator: validateRequire }],
        submitDeptId: [{ validator: validateRequire }],
        submitUserId: [{ validator: validateRequire }],
        roomNo: [{ validator: validateRequire }],
        telephone: [{ validator: validateRequire }],
        priority: [{ validator: validateRequire }],
        flowType: [{ validator: validateRequire }]
      },
      rules1: {
        approveResult: [{ validator: validateRequire }]
      },
      rules2: {
        processUserId: [{ validator: validateRequire }]
      },
      rules3: {
        completed: [{ validator: validateRequire }]
      },
      rules4: {
        passed: [{ validator: validateRequire }]
      },
      rules5: {
        evaluateResult: [{ validator: validateRequire }]
      },
      tempRoute: {},
      processListLoading: false,
      processList: [{ time: '第一次', unit1: '处非办', unit2: '公安局', date: '2021-05-10', limit: '10天', item: '尽快办理', result: '已办结' }, { time: '第二次', unit1: '处非办', unit2: '公安局', date: '2021-05-20', limit: '10天', item: '尽快办理', result: '已办结' }],
      processNow: {},
      mystep: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        this.mystep = this.step
        this.myid = this.infoid
        this.getData(this.myid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getOptions()
    const day = new Date()
    day.setTime(day.getTime())
    console.log(JSON.parse(localStorage.getItem('user')))
    this.roleName = JSON.parse(localStorage.getItem('user')).roleName
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    renew() {
      this.mystep = 'create'
      this.myid = 0
      this.processList = []
      this.processNow = {}
      // this.postForm = Object.assign({}, defaultForm)
      this.postForm1 = Object.assign({}, defaultForm1)
      this.postForm2 = Object.assign({}, defaultForm2)
      this.postForm3 = Object.assign({}, defaultForm3)
      this.postForm4 = Object.assign({}, defaultForm4)
      this.postForm5 = Object.assign({}, defaultForm5)
      this.postForm.id = null
      this.getUsers()
      this.postForm.flowType = this.postForm.flowType === 1 ? '0501' : '0502'
      // submitUserId
      // flowType
      // this.getData(this.myid)
      // this.$$nextTick(()=>{
      //   this.postForm.
      // })
    },
    changeClass(val) {
      this.postForm.priority = this.classCodeOption.find(item => item.value === val).number.split('|')[1]
      this.postForm.flowType = this.classCodeOption.find(item => item.value === val).number.split('|')[0]
    },
    satisfyText(val) {
      if (val) {
        switch (val) {
          case '0301':
            return '满意'
          case '0302':
            return '一般'
          case '0303':
            return '不满意'
        }
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData(id) {
      this.postForm1 = Object.assign({}, defaultForm1)
      this.postForm2 = Object.assign({}, defaultForm2)
      this.getProcessUsers()
      this.infoLoading = true
      this.processListLoading = true
      if (id) {
        this.$http
          .get('/api/workOrder/processDetails?&workOrderId=' + id)
          .then(response => {
            this.infoLoading = false
            this.processListLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result.workOrder
              console.log('this.postForm')
              console.log(this.postForm)
              if (this.postForm.nodeText === '审批工单') {
                this.postForm1 = Object.assign({}, defaultForm1)
              }
              if (this.postForm.nodeText === '分配工单') {
                this.postForm2 = Object.assign({}, defaultForm2)
                this.getProcessUsers()
              }
              this.processList = response.data.result.processList
              this.processNow = this.processList.find(item => (!item.isCompleted && item.userId === JSON.parse(localStorage.getItem('user')).id))
              // console.log('this.processNow')
              // console.log(this.processNow)
              if (this.processNow.nodeText === '处理工单' && !this.processNow.isReaded) {
                this.$http
                  .post('/api/workOrder/updateRead', { flowId: this.processNow.id })
                  .then(response => {
                    if (response.data.success === true) {
                      console.log('已读')
                      this.getData(this.myid)
                    } else {
                      console.log('处理已读失败:' + response.data.message)
                      this.$message({
                        message: '处理已读失败:' + response.data.message,
                        type: 'error'
                      })
                    }
                  })
                  .catch(error => {
                    console.log(error)
                  })
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
            this.processListLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
          if (this.roleName === '法院用户') {
            this.postForm.submitDeptId = JSON.parse(localStorage.getItem('user')).deptId
            this.postForm.submitUserId = JSON.parse(localStorage.getItem('user')).id
            this.postForm.roomNo = JSON.parse(localStorage.getItem('user')).roomNo
            this.postForm.telephone = JSON.parse(localStorage.getItem('user')).phone
            this.deptName = JSON.parse(localStorage.getItem('user')).deptName
            this.realName = JSON.parse(localStorage.getItem('user')).realName
          }
        })
      }
    },
    getOptions() {
      let code = '01'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.priorityOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      code = '04'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.classCodeOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      this.$http
        .get('/api/sysDept/currUnitDepts')
        .then(response => {
          if (response.data.success === true) {
            this.deptOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      code = '05'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.flowTypeOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getUsers() {
      this.$http
        .get('/api/sysUser/deptUsers?deptId=' + this.postForm.submitDeptId)
        .then(response => {
          if (response.data.success === true) {
            this.userOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getProcessUsers() {
      this.$http
        .get('/api/sysUser/getProcessAuthUsers')
        .then(response => {
          if (response.data.success === true) {
            this.processUserOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    setUser() {
      this.postForm.roomNo = this.userOption.find(item => item.id === this.postForm.submitUserId).roomNo
      this.postForm.telephone = this.userOption.find(item => item.id === this.postForm.submitUserId).phone
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const para = {
            faultClassCode: this.postForm.faultClassCode,
            description: this.postForm.description,
            id: this.postForm.id ? this.postForm.id : null,
            submitDeptId: this.postForm.submitDeptId,
            submitUserId: this.postForm.submitUserId,
            roomNo: this.postForm.roomNo,
            telephone: this.postForm.telephone,
            priority: this.postForm.priority,
            flowType: this.postForm.flowType === '0501' ? 1 : 2
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveOrder', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm = Object.assign({}, defaultForm)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm1() {
      this.$refs.postForm1.validate(valid => {
        if (valid) {
          const para = {
            approveContent: this.postForm1.approveContent,
            approveResult: this.postForm1.approveResult,
            orderId: this.myid
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveApproveOrder', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm1 = Object.assign({}, defaultForm1)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm2() {
      this.$refs.postForm2.validate(valid => {
        if (valid) {
          const para = {
            processUserId: this.postForm2.processUserId,
            orderId: this.myid
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveDispatchOrder', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm2 = Object.assign({}, defaultForm2)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm3() {
      this.$refs.postForm3.validate(valid => {
        if (valid) {
          const para = {
            analysis: this.postForm3.analysis,
            solving: this.postForm3.solving,
            completed: this.postForm3.completed,
            orderId: this.myid
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveProcessOrder', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm3 = Object.assign({}, defaultForm3)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm4() {
      this.$refs.postForm4.validate(valid => {
        if (valid) {
          const para = {
            passed: this.postForm4.passed,
            closeReason: this.postForm4.closeReason,
            orderId: this.myid
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveCloseOrder', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm4 = Object.assign({}, defaultForm4)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm5() {
      this.$refs.postForm5.validate(valid => {
        if (valid) {
          const para = {
            evaluateResult: this.postForm5.evaluateResult,
            orderId: this.myid
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveEvaluate', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm5 = Object.assign({}, defaultForm5)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
